# -*- coding: utf-8 -*-

import time
from datetime import datetime
import uuid,random
from method import *
from log import *


def login(userNumber):
    url = get_url('login')
    headers = get_headers('login')
    data = get_data('login')
    data['userNumber']=userNumber
    expect = get_expect('login')
    ree = send_requests('login', url, data, headers)
    a1 = json.loads(ree.text)
    token = a1['data']['token']
    return token

def check(flow_number,add_trans,environment):

    write_yaml(environment)
    logger.info('审批开始，请等待！！！')
    if environment=='uat':
        conn = mysql('uat')
        cursor = conn.cursor()
    if environment=='154':
        conn = mysql('154')
        cursor = conn.cursor()
    # 查询流程ID
    sql5 = "SELECT audit_id FROM  audit  WHERE flow_number='%s';"%(flow_number)
    cursor.execute(sql5)
    conn.commit()
    result = cursor.fetchall()
    for i in result:
        audit_id = i[0]
    # print('流程ID:' + str(audit_id))
    logger.info('流程ID:' + str(audit_id))
    token = login('20280')

    #获取流程审批节点信息
    url=get_url('getAuditConfig1')+str(audit_id)
    headers= get_headers('getAuditConfig1')
    headers['Authorization'] = token
    payload=get_data('getAuditConfig1')
    ree = send_requests('getAuditConfig1', url=url, data=payload, headers=headers)
    res=json.loads(ree.text)
    # print(res)
    # print(res['data'][1]['auditerName'])
    list1=[]

    for i in res['data']:
        list1.clear()
        if i['auditNodeType']=='发起节点':
            pass
        if i['auditNodeType']=='抄送节点':
            pass
        if i['auditNodeType']=='审批节点':
            list1.append(i['auditerName'])
            l = str(list1)
            str1 = l[2:-2]
            list1 = str1.split(',')
            # print(list1)
            logger.info(list1)
            # 查询流程，拿到相关字段
            url1 = get_url('findAudit')
            headers1 = get_headers('findAudit')
            headers1['Authorization'] = token
            data1 = get_data('findAudit')
            data1['auditId'] = audit_id
            expect1 = get_expect('findAudit')
            ree = send_requests('findAudit', url=url1, data=data1, headers=headers1)
            a1 = json.loads(ree.text)

            auditNodeId = a1['data']['auditNodeId']
            auditOrder = a1['data']['auditOrder']
            bizId=a1['data']['bizId']

            # 判断当前审批人做不做加签/转审操作
            # 1代表加签且转审
            if add_trans == 1:
                # 按节点中的审批人，逐一进行审批
                for m in list1:

                    user_number = ''
                    sql = "SELECT user_number from sys_user where user_name IN('%s');" % (m)
                    cursor.execute(sql)
                    conn.commit()
                    result = cursor.fetchall()
                    for i in result:
                        user_number = i[0]
                    logger.info(user_number)
                    token_new = login(user_number)
                    logger.info(user_number+':'+'需要加签且转审')
                    body_data = upload_file(bizId, audit_id, auditNodeId, token_new,2) #上传n个附件，用于加签/转审-审批附件
                    # 加签，可以加多个
                    add_name = []

                    for i in range(1):
                        userr=[]
                        aa=random.choice(user)
                        userr.append(aa)
                        user.remove(aa)
                        url = get_url('addSignature')
                        headers = get_headers('addSignature')
                        headers['Authorization'] = token_new
                        expect =get_expect('addSignature')
                        data = get_data('addSignature')
                        data['attachments'] = body_data
                        data['auditId'] = audit_id
                        data['auditReapprovalUsers']=userr
                        data['remark']='加签加签加签加签加签加签加签加签加签加签加签加签加签加签加签加签加签加加加加'
                        logger.info(data)
                        ree = send_requests('addSignature', url=url, data=data, headers=headers)
                        a = json.loads(ree.text)
                        if a['status'] == expect:
                            logger.info(str(userr[i]['userName'])+':'+'加签成功')
                            add_name.append(userr[i]['userNumber'])

                        if a['message'] == '加签失败，当前用户总加签人数超过5人！':
                            logger.error(str(userr[i]['userName'])+':'+'加签失败，当前用户总加签人数超过5人！')
                        # logger.info(user)

                    #转审，只能转一次
                    useryy=[]
                    uu = random.choice(user1)
                    useryy.append(uu)
                    user1.remove(uu)
                    url = get_url('transferApproval')
                    headers = get_headers('transferApproval')
                    headers['Authorization'] = token_new
                    expect = get_expect('transferApproval')
                    data = get_data('transferApproval')
                    data['attachments'] = body_data
                    data['auditId'] = audit_id
                    data['auditReapprovalUsers'] = useryy
                    data['remark'] = '转审转审转审'
                    logger.info(data)
                    ree = send_requests( 'transferApproval', url=url, data=data, headers=headers)
                    a = json.loads(ree.text)
                    if a['status'] == expect:
                        logger.info(str(useryy[i]['userName']) + ':' + '转审成功')
                        add_name.append(useryy[i]['userNumber'])
                    else:
                        logger.info(str(useryy[i]['userName']) + ':' + '转审失败')
                    # logger.info(user)
                    #把加签/转审的人完成流程审批
                    for i in add_name:
                        token_new = login(i)
                        body_data = upload_file(bizId, audit_id, auditNodeId, token_new, 1)  # 上传n个附件
                        # 再次提交上传附件
                        url3 = get_url('uploadFile')
                        headers3 = get_headers('uploadFile')
                        headers3['Authorization'] = token_new
                        expect3 = get_expect('uploadFile')
                        data3 = body_data
                        # print(data3)
                        # logger.info(data3)
                        ree3 = send_requests( 'uploadFile', url=url3, data=data3, headers=headers3)
                        a3 = json.loads(ree3.text)
                        try:
                            # 断言 'status' 的值是否等于 expect
                            assert a3['status'] == expect3
                            # print("附件提交成功")
                            logger.info("附件提交成功")
                        except AssertionError:
                            # print("断言失败：附件提交失败")
                            # print(a3)
                            logger.info("断言失败：附件提交失败")
                            logger.error(a3)

                        time.sleep(1)

                        # 提交审批流程结果和审批意见
                        url2 = get_url('examineApprove')
                        headers2 = get_headers('examineApprove')
                        headers2['Authorization'] = token_new
                        expect2 = get_expect('examineApprove')
                        data2 = get_data('examineApprove')
                        data2['auditId'] = audit_id
                        data2['auditNodeId'] = auditNodeId
                        data2['auditOrder'] = auditOrder
                        # print(data2)
                        logger.info(data2)
                        ree1 = send_requests('examineApprove', url=url2, data=data2, headers=headers2)
                        a2 = json.loads(ree1.text)
                        try:
                            # 断言 'status' 的值是否等于 expect
                            assert a2['status'] == expect2
                            # print("审批意见提交成功")
                            logger.info("审批意见提交成功")
                        except AssertionError:
                            # print("断言失败：审批意见提交失败")
                            # print(a2)
                            logger.info("断言失败：审批意见提交失败")
                            logger.error(a2)
            # 2代表加签，不转审
            if add_trans == 2:
                # 按节点中的审批人，逐一进行审批
                for m in list1:

                    user_number = ''
                    sql = "SELECT user_number from sys_user where user_name IN('%s');" % (m)
                    cursor.execute(sql)
                    conn.commit()
                    result = cursor.fetchall()
                    for i in result:
                        user_number = i[0]
                    logger.info(user_number)
                    token_new = login(user_number)
                    logger.info(user_number + ':' + '需要加签，但不转审')
                    body_data = upload_file(bizId, audit_id, auditNodeId, token_new, 2)  # 上传n个附件，用于加签/转审-审批附件
                    # 加签，可以加多个
                    add_name = []

                    for i in range(1):
                        userr = []
                        aa = random.choice(user)
                        userr.append(aa)
                        user.remove(aa)
                        url = get_url('addSignature')
                        headers = get_headers('addSignature')
                        headers['Authorization'] = token_new
                        expect = get_expect('addSignature')
                        data = get_data('addSignature')
                        data['attachments'] = body_data
                        data['auditId'] = audit_id
                        data['auditReapprovalUsers'] = userr
                        data['remark'] = '加签加签加签加签加签加签加签加签加签加签加签加签加签加签加签加签加签加加加加'
                        logger.info(data)
                        ree = send_requests('addSignature', url=url, data=data, headers=headers)
                        a = json.loads(ree.text)
                        if a['status'] == expect:
                            logger.info(str(userr[i]['userName']) + ':' + '加签成功')
                            add_name.append(userr[i]['userNumber'])

                        if a['message'] == '加签失败，当前用户总加签人数超过5人！':
                            logger.error(str(userr[i]['userName']) + ':' + '加签失败，当前用户总加签人数超过5人！')
                        # logger.info(user)

                    # 把加签+当前操作人完成流程审批
                    add_name.append(user_number)
                    for i in add_name:
                        token_new = login(i)
                        body_data = upload_file(bizId, audit_id, auditNodeId, token_new, 1)  # 上传n个附件
                        # 再次提交上传附件
                        url3 = get_url('uploadFile')
                        headers3 = get_headers('uploadFile')
                        headers3['Authorization'] = token_new
                        expect3 = get_expect('uploadFile')
                        data3 = body_data
                        # print(data3)
                        # logger.info(data3)
                        ree3 = send_requests('uploadFile', url=url3, data=data3, headers=headers3)
                        a3 = json.loads(ree3.text)
                        try:
                            # 断言 'status' 的值是否等于 expect
                            assert a3['status'] == expect3
                            # print("附件提交成功")
                            logger.info("附件提交成功")
                        except AssertionError:
                            # print("断言失败：附件提交失败")
                            # print(a3)
                            logger.info("断言失败：附件提交失败")
                            logger.error(a3)

                        time.sleep(1)

                        # 提交审批流程结果和审批意见
                        url2 = get_url('examineApprove')
                        headers2 =get_headers('examineApprove')
                        headers2['Authorization'] = token_new
                        expect2 = get_expect('examineApprove')
                        data2 = get_data('examineApprove')
                        data2['auditId'] = audit_id
                        data2['auditNodeId'] = auditNodeId
                        data2['auditOrder'] = auditOrder
                        # print(data2)
                        logger.info(data2)
                        ree1 = send_requests('examineApprove', url=url2, data=data2, headers=headers2)
                        a2 = json.loads(ree1.text)
                        try:
                            # 断言 'status' 的值是否等于 expect
                            assert a2['status'] == expect2
                            # print("审批意见提交成功")
                            logger.info("审批意见提交成功")
                        except AssertionError:
                            # print("断言失败：审批意见提交失败")
                            # print(a2)
                            logger.info("断言失败：审批意见提交失败")
                            logger.error(a2)
            # 3代表不加签，不转审
            if add_trans == 3:
                # 按节点中的审批人，逐一进行审批
                for m in list1:
                    user_number = ''
                    sql = "SELECT user_number from sys_user where user_name IN('%s');" % (m)
                    cursor.execute(sql)
                    conn.commit()
                    result = cursor.fetchall()
                    for i in result:
                        user_number = i[0]
                    logger.info(user_number)
                    token_new = login(user_number)
                    logger.info(user_number + ':' + '不需要加签，不转审')
                    body_data = upload_file(bizId, audit_id, auditNodeId, token_new, 1)  # 上传n个附件
                    # 再次提交上传附件
                    url3 = get_url('uploadFile')
                    headers3 = get_headers('uploadFile')
                    headers3['Authorization'] = token_new
                    expect3 = get_expect('uploadFile')
                    data3 = body_data
                    # print(data3)
                    # logger.info(data3)
                    ree3 = send_requests('uploadFile', url=url3, data=data3, headers=headers3)
                    a3 = json.loads(ree3.text)
                    try:
                        # 断言 'status' 的值是否等于 expect
                        assert a3['status'] == expect3
                        # print("附件提交成功")
                        logger.info("附件提交成功")
                    except AssertionError:
                        # print("断言失败：附件提交失败")
                        # print(a3)
                        logger.info("断言失败：附件提交失败")
                        logger.error(a3)

                    time.sleep(1)

                    # 提交审批流程结果和审批意见
                    url2 = get_url('examineApprove')
                    headers2 = get_headers('examineApprove')
                    headers2['Authorization'] = token_new
                    expect2 = get_expect('examineApprove')
                    data2 = get_data('examineApprove')
                    data2['auditId'] = audit_id
                    data2['auditNodeId'] = auditNodeId
                    data2['auditOrder'] = auditOrder
                    # print(data2)
                    logger.info(data2)
                    ree1 = send_requests('examineApprove', url=url2, data=data2, headers=headers2)
                    a2 = json.loads(ree1.text)
                    try:
                        # 断言 'status' 的值是否等于 expect
                        assert a2['status'] == expect2
                        # print("审批意见提交成功")
                        logger.info("审批意见提交成功")
                    except AssertionError:
                        # print("断言失败：审批意见提交失败")
                        # print(a2)
                        logger.info("断言失败：审批意见提交失败")
                        logger.error(a2)
            # 4代表不加签，只转审
            if add_trans == 4:
                # 按节点中的审批人，逐一进行审批
                for m in list1:

                    user_number = ''
                    sql = "SELECT user_number from sys_user where user_name IN('%s');" % (m)
                    cursor.execute(sql)
                    conn.commit()
                    result = cursor.fetchall()
                    for i in result:
                        user_number = i[0]
                    logger.info(user_number)
                    token_new = login(user_number)
                    logger.info(user_number+':'+'不需要加签，只转审')
                    body_data = upload_file(bizId, audit_id, auditNodeId, token_new,2) #上传n个附件，用于加签/转审-审批附件

                    add_name = []
                    #转审，只能转一次
                    useryy=[]
                    uu = random.choice(user1)
                    useryy.append(uu)
                    user1.remove(uu)
                    url = get_url('transferApproval')
                    headers = get_headers('transferApproval')
                    headers['Authorization'] = token_new
                    expect = get_expect('transferApproval')
                    data = get_data('transferApproval')
                    data['attachments'] = body_data
                    data['auditId'] = audit_id
                    data['auditReapprovalUsers'] = useryy
                    data['remark'] = '转审转审转审'
                    logger.info(data)
                    ree = send_requests('transferApproval', url=url, data=data, headers=headers)
                    a = json.loads(ree.text)
                    if a['status'] == expect:
                        logger.info(str(useryy[0]['userName']) + ':' + '转审成功')
                        add_name.append(useryy[0]['userNumber'])
                    else:
                        logger.info(str(useryy[0]['userName']) + ':' + '转审失败')
                    # logger.info(user)

                    #把转审的人完成流程审批
                    for i in add_name:
                        token_new = login(i)
                        body_data = upload_file(bizId, audit_id, auditNodeId, token_new, 1)  # 上传n个附件
                        # 再次提交上传附件
                        url3 = get_url('uploadFile')
                        headers3 = get_headers('uploadFile')
                        headers3['Authorization'] = token_new
                        expect3 = get_expect('uploadFile')
                        data3 = body_data
                        # print(data3)
                        # logger.info(data3)
                        ree3 = send_requests('uploadFile', url=url3, data=data3, headers=headers3)
                        a3 = json.loads(ree3.text)
                        try:
                            # 断言 'status' 的值是否等于 expect
                            assert a3['status'] == expect3
                            # print("附件提交成功")
                            logger.info("附件提交成功")
                        except AssertionError:
                            # print("断言失败：附件提交失败")
                            # print(a3)
                            logger.info("断言失败：附件提交失败")
                            logger.error(a3)

                        time.sleep(1)

                        # 提交审批流程结果和审批意见
                        url2 = get_url('examineApprove')
                        headers2 = get_headers('examineApprove')
                        headers2['Authorization'] = token_new
                        expect2 = get_expect('examineApprove')
                        data2 =get_data('examineApprove')
                        data2['auditId'] = audit_id
                        data2['auditNodeId'] = auditNodeId
                        data2['auditOrder'] = auditOrder
                        # print(data2)
                        logger.info(data2)
                        ree1 = send_requests('examineApprove', url=url2, data=data2, headers=headers2)
                        a2 = json.loads(ree1.text)
                        try:
                            # 断言 'status' 的值是否等于 expect
                            assert a2['status'] == expect2
                            # print("审批意见提交成功")
                            logger.info("审批意见提交成功")
                        except AssertionError:
                            # print("断言失败：审批意见提交失败")
                            # print(a2)
                            logger.info("断言失败：审批意见提交失败")
                            logger.error(a2)

    # 查询流程最终审批状态
    sql6 = "SELECT audit_status FROM audit WHERE audit_id=%s;" % (audit_id)
    cursor.execute(sql6)
    conn.commit()
    result = cursor.fetchall()
    for i in result:
        audit_status = i[0]
    # print(audit_status)
    logger.info('流程状态为：'+str(audit_status))
    if audit_status == 0:
        # print("流程没审批完，请继续！")
        logger.info({ "message": "success","status": 200, "data": "流程审批报错了，请查看日志！"})
        logger.info('本次审批结束！')
        return { "message": "success","status": 200, "data": "流程审批报错了，请查看日志！"}


    if audit_status == 1:
        # print('流程审核通过啦！')
        logger.info({ "message": "success","status": 200, "data": '流程审核通过啦！'})
        logger.info('本次审批结束！')
        return { "message": "success","status": 200, "data": '流程审核通过啦！'}




















